﻿// <copyright file="CreateSchemaButton.cs" company="City of Portland, BES-ASM">
// </copyright>
// <summary>CreateSchemaButton class</summary>

namespace BESASM.EMGAATS.UI.ArcMap
{
  using System;
  using System.Collections.Generic;
  using System.IO;
  using System.Text;
  using BESASM.EMGAATS.Arc;
  using BESASM.EMGAATS.DataAccess;
  using ESRI.ArcGIS.CatalogUI;
  using ESRI.ArcGIS.DataSourcesGDB;
  using ESRI.ArcGIS.esriSystem;
  using ESRI.ArcGIS.Geodatabase;

  /// <summary>
  /// A button for creating an empty EMGAATS data schema in a geodatabase.
  /// </summary>
  public class CreateSchemaButton : ESRI.ArcGIS.Desktop.AddIns.Button
  {
    /// <summary>
    /// Called when the button is clicked by ArcMap
    /// </summary>
    protected override void OnClick()
    {
      FormsUtility.SafeExecute(delegate
      {
        ArcMap.Application.CurrentTool = null;
        this.InternalOnClick();
      });
    }

    /// <summary>
    /// Called when controls are updated by ArcMap.
    /// </summary>
    protected override void OnUpdate()
    {
      this.Enabled = true;
    }

    private void InternalOnClick()
    {
      IGxDialog gxDialog = new GxDialogClass();
      gxDialog.Title = "Create New EMGAATS Schema";
      gxDialog.ObjectFilter = new FileGeodatabaseFilterWrapper();

      if (gxDialog.DoModalSave(ArcMap.Application.hWnd))
      {
        IWorkspaceFactory factory = new FileGDBWorkspaceFactoryClass();
        if (gxDialog.ReplacingObject)
        {
          IWorkspace existing = factory.OpenFromFile(System.IO.Path.Combine(gxDialog.FinalLocation.FullName, gxDialog.Name), ArcMap.Application.hWnd);
          ((IDataset)existing).Delete();
        }

        IWorkspaceName workspaceName = factory.Create(gxDialog.FinalLocation.FullName, gxDialog.Name, null, ArcMap.Application.hWnd);
        IWorkspace workspace = ((IName)workspaceName).Open() as IWorkspace;

        ModelDataAccess dataAccess = new ModelDataAccess();
        dataAccess.Workspace = workspace;
        dataAccess.CreateNetworkSchema();
      }
      else
      {
        return;
      }
    }
  }
}
